#匹配.com和.cn后缀的URL网址
import re
pattern = '[a-zA-Z]+://[^\s]*[.com|.cn]'
string = "<a href='http://www.baidu.com'>百度首页</a>"#协议名http+主机名
result = re.search(pattern,string)
print(result)

#匹配电话号码
pattern='\d{4}-\d{7}|\d{3}-\d{8}'
string='dagduayhgbd0715-3533537djahda137-59903699876841dadxad'
result = re.compile(pattern).findall(string)
print(result)

#匹配电子邮件地址
string='abcdef'
pattern1='abc'
pattern2='a  b  c'
print(re.search(pattern1,string))
print(re.search(pattern2,string))
#由此可见正则表达式里面打空格/缩进，对输出结果有影响！！！！！！！！

string= r"<a href='http://www.baidu.com'>百度首页</a><br><a href='mailto:c-e+o@iqi-anyue.com.cn'>" \
        "电子邮件地址</a>"+r"<br><a href='mailto:810968734@qq.com'>" \
        "电子邮件地址</a>"
pattern='\w+([+-.]\w+)*@\w+([.-]\w+)*\.\w+([.-]\w+)*'
pattern1='\w+(?=[+-.]\w+)*@\w+(?=[.-]\w+)*\.\w+(?=[.-]\w+)*'
pattern2='(\w+(?=[+-.]\w+)*@\w+(?=[.-]\w+)*\.\w+(?=[.-]\w+)*)+?'
pattern3=r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)"

print('search-pattern:' + str(re.search(pattern,string)))
print('findall-pattern:' + str(re.findall(pattern,string)))
print('findall-pattern1:' + str(re.findall(pattern1,string)))
print('findall-pattern2:' + str(re.findall(pattern2,string)))
print('findall-pattern3:' + str(re.findall(pattern3,string)))
"""
https://blog.csdn.net/m0_37360684/article/details/84141176
在使用findall()方法时的“坑”：注意正则表达式中括号()的使用
（1）正则表达式中当没有括号时，正常匹配：
（2）正则表达式中有一个括号时，其输出的内容就是括号匹配到的内容，而不是整个表达式所匹配到的结果：
"""

print(re.compile(pattern).findall(string))
print(re.compile(pattern1).findall(string))

import re
line ='192.168.0.1 25/Oct/2012:14:46:34 "GET /api HTTP/1.1" 200 44 "http://abc.com/search" "Mozilla/5.0"'
reg = re.compile('^(?P<remote_ip>[^ ]*) (?P<date>[^ ]*) "(?P<request>[^"]*)" (?P<status>[^ ]*) (?P<size>[^ ]*) "(?P<referrer>[^"]*)" "(?P<user_agent>[^"]*)"')
regMatch = reg.match(line)
linebits = regMatch.groupdict()
print (linebits)
for k, v in linebits.items() :
    print (k+": "+v)
